package com.currency.mall.ui.main;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.currency.mall.R;
import com.currency.mall.adapter.BannerAdapter;
import com.currency.mall.adapter.HotTradedapter;
import com.currency.mall.adapter.ShareIndexAdapter;
import com.currency.mall.di.component.DaggerHomeComponent;
import com.currency.mall.di.modlue.HomeModule;
import com.currency.mall.entity.BannerBean;
import com.currency.mall.entity.OptimalOrderBean;
import com.currency.mall.entity.SecurityBean;
import com.currency.mall.event.MainEvent;
import com.currency.mall.ui.my.recharge.RechargeActivity;
import com.currency.mall.ui.web.WebViewActivity;
import com.currency.mall.widget.HorizontalPageLayoutManager;
import com.mifengs.commonbase.base.BaseFragment;
import com.mifengs.commonbase.util.PreferenceUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2018/12/4.
 */

public class HomeFragment extends BaseFragment<HomeFragmentPresent> implements HomeFragmentContract.View {


    Unbinder unbinder;
    @BindView(R.id.rv_banner)
    RecyclerView rvBanner;
    @BindView(R.id.rv_trading)
    RecyclerView rvTrading;
    @BindView(R.id.rv_hot_trade)
    RecyclerView rvHotTrade;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private BannerAdapter mBannerAdapter;
    private ShareIndexAdapter mShareIndexAdapter;
    private HotTradedapter mHotTradedapter;
    private ScheduledExecutorService service;
    public HomeFragment() {
    }

    public static HomeFragment newInstance() {
        HomeFragment fragment = new HomeFragment();
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View mView = inflater.inflate(R.layout.fragment_home, container, false);
        unbinder = ButterKnife.bind(this, mView);
        init();
        return mView;
    }


    @Override
    public void initInjector() {
        DaggerHomeComponent.builder()
                .homeModule(new HomeModule(this))
                .build()
                .inject(this);
    }

    private void init() {
        refreshLayout.setEnableLoadMore(false);
        rvBanner.setLayoutManager(new LinearLayoutManager(getContext()));
        rvBanner.setNestedScrollingEnabled(false);
        mBannerAdapter = new BannerAdapter(null, getContext());
        rvBanner.setAdapter(mBannerAdapter);
        HorizontalPageLayoutManager horizontalPageLayoutManager = new HorizontalPageLayoutManager(1, 3);
        rvTrading.setLayoutManager(horizontalPageLayoutManager);
        rvTrading.setNestedScrollingEnabled(false);
        mShareIndexAdapter = new ShareIndexAdapter(null, getContext());
        rvTrading.setAdapter(mShareIndexAdapter);

        rvHotTrade.setLayoutManager(new LinearLayoutManager(getContext()));
        rvHotTrade.setNestedScrollingEnabled(false);
        mHotTradedapter = new HotTradedapter(null, getContext());
        rvHotTrade.setAdapter(mHotTradedapter);

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (refreshLayout != null) {
                    mPresenter.getBanner();
                    mPresenter.securityInfo();
                    mPresenter.getOptimalOrder();
                }
            }
        });
        service = Executors.newScheduledThreadPool(1);
        service.scheduleAtFixedRate(new VisibleScheduledExecutor(), 10, 5, TimeUnit.SECONDS);

        mPresenter.getBanner();
        mPresenter.securityInfo();
        mPresenter.getOptimalOrder();
    }



    Handler mHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (PreferenceUtils.getLoginStatus())
                        mPresenter.securityInfo();
                    break;
            }
        }
    };

    class VisibleScheduledExecutor implements Runnable {

        @Override
        public void run() {
            Message msg = new Message();
            msg.what = 1;
            mHandle.sendMessage(msg);
        }
    }

    public void finishRefresh() {
        if (refreshLayout != null)
            refreshLayout.finishRefresh();
    }

    @Override
    public void setSecurityData(List<SecurityBean.SecurityInfo> securityInfos) {
        mShareIndexAdapter.setNewData(securityInfos);
    }

    @Override
    public void setOptimalOrder(List<OptimalOrderBean.OptimalOrderInfo> orderInfoList) {
        mHotTradedapter.setNewData(orderInfoList);
    }

    @Override
    public void setBanner(List<BannerBean> banners) {
        mBannerAdapter.setNewData(banners);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        shutDownService();
    }

    private void shutDownService() {
        if(service !=null){
            try {
                service.shutdown();
                if (!service.awaitTermination(1, TimeUnit.MILLISECONDS)) {
                    service.shutdownNow();
                }
            } catch (Exception exception) {
                service.shutdownNow();
            }
        }


    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            shutDownService();
        } else {
            service = Executors.newScheduledThreadPool(1);
            service.scheduleAtFixedRate(new VisibleScheduledExecutor(), 10, 5, TimeUnit.SECONDS);
        }
    }

    @OnClick({R.id.tv_inquiry, R.id.tv_optional, R.id.tv_recharge, R.id.tv_guide})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_inquiry:
                EventBus.getDefault().post(new MainEvent(MainEvent.TAB_INQUIRY));
                break;
            case R.id.tv_optional:
                EventBus.getDefault().post(new MainEvent(MainEvent.TAB_OPTIONAL));
                break;
            case R.id.tv_recharge:
                startActivity(new Intent(getContext(), RechargeActivity.class));
                break;
            case R.id.tv_guide:
                Intent intent = new Intent(getContext(), WebViewActivity.class);
                intent.putExtra("ExtraWebPath", "http://150.109.125.51/help/index.html");
                intent.putExtra("ExtraWebTitle", "帮助中心");
                startActivity(intent);
                break;
        }
    }
}
